package elitech.vietnam.myfashion;

import java.io.IOException;

import org.xmlpull.v1.XmlPullParserException;

import com.google.android.gms.gcm.GoogleCloudMessaging;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnKeyListener;
import android.view.inputmethod.InputMethodManager;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import elitech.vietnam.myfashion.dialog.ForgotPasswordDialog;
import elitech.vietnam.myfashion.dialog.WarningDialog;
import elitech.vietnam.myfashion.doinbackground.CallServiceTask;
import elitech.vietnam.myfashion.wsclient.Utilities;

public class LoginActivity extends Activity implements OnClickListener,
		OnFocusChangeListener {

	private static final int USERNAMEBLANK = 0;
	private static final int EMAILINVALID = 1;
	private static final int EMAILCONNECTERROR = 2;
	private static final int EMAILEXISTED = 3;
	private static final int PASSINVALID = 4;
	private static final int CONFIRMDIFFERENT = 5;

	private Context mContext;
	private LinearLayout layLogin, laySignUp;
	private Button btnLogin, btnSignUp;
	private TextView txtWarn, txtSignup, txtForgot;
	private EditText txtEmail, txtPass, txtUserName, txtEmailSignUp,
			txtPassSignUp, txtConfirmPass;
	private ProgressDialog mLoadingDialog;
	private boolean isSignUpLayoutShow = false;
	private boolean[] mErrorList = { true, true, true, true, true, true };
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.mContext = this;
		getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
		setContentView(R.layout.activity_main);
		LayoutInit();
	}

	private void LayoutInit() {
		layLogin = (LinearLayout) findViewById(R.id.login_layLogin);
		laySignUp = (LinearLayout) findViewById(R.id.login_laySignUp);

		txtWarn = (TextView) findViewById(R.id.login_txtWarn);
		txtSignup = (TextView) findViewById(R.id.login_txtSignup);
		txtForgot = (TextView) findViewById(R.id.login_btnForgot);
		
		txtEmail = (EditText) findViewById(R.id.login_txtEmail);
		txtPass = (EditText) findViewById(R.id.login_txtPassword);

		txtUserName = (EditText) findViewById(R.id.login_txtUserName);
		txtEmailSignUp = (EditText) findViewById(R.id.login_txtEmailSignup);
		txtPassSignUp = (EditText) findViewById(R.id.login_txtPasswordSignup);
		txtConfirmPass = (EditText) findViewById(R.id.login_txtConfirmPassword);

		btnLogin = (Button) findViewById(R.id.login_btnLogin);
		btnSignUp = (Button) findViewById(R.id.login_btnSignup);

		btnLogin.setOnClickListener(this);
		btnSignUp.setOnClickListener(this);
		txtSignup.setOnClickListener(this);
		txtForgot.setOnClickListener(this);
		
		txtUserName.setOnFocusChangeListener(this);
		txtEmailSignUp.setOnFocusChangeListener(this);
		txtPassSignUp.setOnFocusChangeListener(this);
		txtConfirmPass.setOnKeyListener(new OnKeyListener() {

			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				String confirm = txtConfirmPass.getText().toString();
				if (txtConfirmPass.getText().length() == 0) {
					txtConfirmPass.setBackgroundResource(R.color.white);
				} else if (txtPassSignUp.getText().toString().equals(confirm)) {
					txtConfirmPass.setBackgroundResource(R.color.light_green);
					mErrorList[CONFIRMDIFFERENT] = true;
				} else {
					txtConfirmPass.setBackgroundResource(R.color.pink);
					mErrorList[CONFIRMDIFFERENT] = false;
				}
				txtWarn.setText(getError());
				return false;
			}
		});
		
		mLoadingDialog = new ProgressDialog(this);
		mLoadingDialog.setCancelable(false);
		mLoadingDialog.setMessage(getString(R.string.loading));

	}

	private String getError() {
		int key = -1;
		for (int i = 0; i < mErrorList.length; i++) {
			if (!mErrorList[i]) {
				key = i;
				break;
			}
		}
		switch (key) {
		case USERNAMEBLANK:
			return getString(R.string.nameblank);
		case EMAILINVALID:
			return getString(R.string.emailinvalid);
		case EMAILCONNECTERROR:
			return getString(R.string.connecterror);
		case EMAILEXISTED:
			return getString(R.string.emailexist);
		case PASSINVALID:
			return getString(R.string.passinvalid);
		case CONFIRMDIFFERENT:
			return getString(R.string.confirmpassworddifferent);
		default:
			return "";
		}
	}

	@Override
	public void onClick(View v) {
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(txtEmail.getWindowToken(), 0);
		imm.hideSoftInputFromWindow(txtPass.getWindowToken(), 0);
		imm.hideSoftInputFromWindow(txtUserName.getWindowToken(), 0);
		imm.hideSoftInputFromWindow(txtEmailSignUp.getWindowToken(), 0);
		imm.hideSoftInputFromWindow(txtPassSignUp.getWindowToken(), 0);

		switch (v.getId()) {
		case R.id.login_btnLogin:
			if (txtEmail.getText().length() == 0) {
				new WarningDialog(mContext, getResources().getString(
						R.string.emailblank)).show();
			} else if (txtPass.getText().length() == 0)
				new WarningDialog(mContext, getResources().getString(
						R.string.passblank)).show();
			else {
				new CallServiceTask() {
					private int rs = -2;

					protected void onPreExecute() {
						mLoadingDialog.show();
					};

					public void work() {
						int rs1 = 0;
						try {
							rs = service.login(txtEmail.getText().toString(),
									txtPass.getText().toString());
							Log.w("Shopping", "Login1: " + rs);
							if (rs > 0) {
								String GCMID = GoogleCloudMessaging.getInstance(mContext).register(MainActivity.GCM_SENDER_ID);
								Log.w("Shopping", "Login2: " + GCMID);
								rs1 = service.updateGCMID(rs, GCMID);
								if (rs1 <= 0)
									rs = -2;
							}
							Log.w("Shopping", "Login3: " + rs);
						} catch (IOException e) {
							e.printStackTrace();
						} catch (XmlPullParserException e) {
							e.printStackTrace();
						}
					};

					protected void onPostExecute(Void result) {
						mLoadingDialog.dismiss();
						if (rs == -2) {
							new WarningDialog(mContext, getResources()
									.getString(R.string.connecterror)).show();
							return;
						}
						if (rs == -1) {
							new WarningDialog(mContext, getResources()
									.getString(R.string.emailnotexist)).show();
							return;
						}
						if (rs == -0) {
							new WarningDialog(mContext, getResources()
									.getString(R.string.passwrong)).show();
							return;
						}
						Intent returnIntent = new Intent();
						returnIntent.putExtra("Id", rs);
						setResult(RESULT_OK, returnIntent);
						finish();
					};
				}.execute();
			}
			break;
		case R.id.login_txtSignup:
			isSignUpLayoutShow = true;
			laySignUp.setVisibility(View.VISIBLE);
			layLogin.setVisibility(View.GONE);
			txtSignup.setVisibility(View.GONE);
			txtForgot.setVisibility(View.GONE);
			btnLogin.setVisibility(View.GONE);
			btnSignUp.setVisibility(View.VISIBLE);
			break;
		case R.id.login_btnSignup:
			if (!isSignUpLayoutShow) {

			} else {
				if (txtUserName.getText().toString().trim().length() == 0) {
					txtUserName.setBackgroundResource(R.color.pink);
					if (txtWarn.getText().length() == 0)
						txtWarn.setText(getString(R.string.nameblank));
					txtUserName.setText("");
					break;
				} else {
					if (txtWarn.getText().equals(getString(R.string.nameblank))) {
						txtWarn.setText("");
						txtUserName.setBackgroundResource(R.color.light_green);
						mErrorList[USERNAMEBLANK] = true;
						break;
					}
				}

				if (txtEmailSignUp.getText().length() == 0) {
					txtEmailSignUp.setBackgroundResource(R.color.pink);
					if (txtWarn.getText().length() == 0)
						txtWarn.setText(getString(R.string.emailblank));
					break;
				} else {
					if (txtWarn.getText()
							.equals(getString(R.string.emailblank))) {
						txtWarn.setText("");
						mErrorList[EMAILINVALID] = true;
						new CallServiceTask() {
							private int rs = -2;

							public void work() {
								try {
									rs = service.checkEmail(txtEmailSignUp
											.getText().toString());
								} catch (IOException e) {
								} catch (XmlPullParserException e) {
								}
							};

							protected void onPostExecute(Void result) {
								if (rs == -2) {
									txtEmailSignUp
											.setBackgroundResource(R.color.pink);
									mErrorList[EMAILCONNECTERROR] = false;
									txtWarn.setText(getError());
									return;
								}
								if (rs == 1) {
									txtEmailSignUp
											.setBackgroundResource(R.color.pink);
									mErrorList[EMAILEXISTED] = false;
									txtWarn.setText(getError());
									return;
								} else {
									mErrorList[EMAILCONNECTERROR] = true;
									mErrorList[EMAILEXISTED] = true;
									mErrorList[EMAILINVALID] = true;
									txtEmailSignUp
											.setBackgroundResource(R.color.light_green);
									txtWarn.setText(getError());
								}
							};
						}.execute();
						break;
					}
				}

				if (txtPassSignUp.getText().length() == 0) {
					txtPassSignUp.setBackgroundResource(R.color.pink);
					if (txtWarn.getText().length() == 0)
						txtWarn.setText(getString(R.string.passblank));
					break;
				} else {
					if (txtWarn.getText().equals(getString(R.string.passblank))){
						txtWarn.setText("");
						String password = txtPassSignUp.getText().toString();
						if (txtPassSignUp.getText().length() == 0) {
							txtPassSignUp.setBackgroundResource(R.color.white);
						} else if (Utilities.checkValPass(password)) {
							txtPassSignUp.setBackgroundResource(R.color.light_green);
							mErrorList[PASSINVALID] = true;
						} else {
							txtPassSignUp.setBackgroundResource(R.color.pink);
							mErrorList[PASSINVALID] = false;
						}
						txtWarn.setText(getError());
						break;
					}
				}

				if (txtConfirmPass.getText().length() == 0) {
					txtConfirmPass.setBackgroundResource(R.color.pink);
					if (txtWarn.getText().length() == 0)
						txtWarn.setText(getString(R.string.passblank));
					break;
				} else {
					if (txtWarn.getText().equals(getString(R.string.passblank))){
						txtWarn.setText("");
						break;
					}
					
				}

				if (getError().equals("")) {
					new CallServiceTask() {
						private int rs = -2;

						protected void onPreExecute() {
							mLoadingDialog.show();
						};

						public void work() {
							try {
								rs = service.signUp(txtUserName.getText()
										.toString(), txtEmailSignUp.getText()
										.toString(), txtPassSignUp.getText()
										.toString());
							} catch (IOException e) {
							} catch (XmlPullParserException e) {
							}
						};

						protected void onPostExecute(Void result) {
							mLoadingDialog.dismiss();
							if (rs == -2 || rs == 0)
								new WarningDialog(mContext, getResources()
										.getString(R.string.connecterror))
										.show();
							else {
								new WarningDialog(mContext, getResources()
										.getString(R.string.signupsuccessful))
										.show();
								txtEmail.setText(txtEmailSignUp.getText()
										.toString());
								txtPass.setText(txtPassSignUp.getText()
										.toString());

								txtUserName.setText("");
								txtEmailSignUp.setText("");
								txtPassSignUp.setText("");
								txtConfirmPass.setText("");

								isSignUpLayoutShow = false;
								laySignUp.setVisibility(View.GONE);
								layLogin.setVisibility(View.VISIBLE);
								txtSignup.setVisibility(View.VISIBLE);
								txtForgot.setVisibility(View.VISIBLE);
								btnLogin.setVisibility(View.VISIBLE);
								btnSignUp.setVisibility(View.GONE);
							}
						};
					}.execute();
				}
			}
			break;
		case R.id.login_btnForgot:
			new ForgotPasswordDialog(mContext).show();
			break;
		}
	}

	@Override
	public void onBackPressed() {
		if (isSignUpLayoutShow) {
			isSignUpLayoutShow = false;
			laySignUp.setVisibility(View.GONE);
			layLogin.setVisibility(View.VISIBLE);
			txtSignup.setVisibility(View.VISIBLE);
			btnLogin.setVisibility(View.VISIBLE);
			txtForgot.setVisibility(View.VISIBLE);
			btnSignUp.setVisibility(View.GONE);
			txtWarn.setText("");
			return;
		} else
			super.onBackPressed();
	}

	@Override
	public void onFocusChange(View v, boolean hasFocus) {
		if (!hasFocus) {
			switch (v.getId()) {
			case R.id.login_txtUserName:
				txtUserName.setTextColor(Color.BLACK);
				if (txtUserName.getText().toString().trim().length() == 0) {
					txtUserName.setBackgroundResource(R.color.pink);
					txtUserName.setText("");
					mErrorList[USERNAMEBLANK] = false;
				} else {
					txtUserName.setBackgroundResource(R.color.light_green);
					mErrorList[USERNAMEBLANK] = true;
				}
				txtWarn.setText(getError());
				break;
			case R.id.login_txtEmailSignup:
				final String email = txtEmailSignUp.getText().toString();
				txtEmailSignUp.setTextColor(Color.BLACK);
				if (txtEmailSignUp.getText().length() == 0) {
					txtEmailSignUp.setBackgroundResource(R.color.white);
				} else if (Utilities.checkEmailValid(email)) {
					mErrorList[EMAILINVALID] = true;
					new CallServiceTask() {
						private int rs = -2;

						public void work() {
							try {
								rs = service.checkEmail(email);
							} catch (IOException e) {
							} catch (XmlPullParserException e) {
							}
						};

						protected void onPostExecute(Void result) {
							if (rs == -2) {
								txtEmailSignUp
										.setBackgroundResource(R.color.pink);
								mErrorList[EMAILCONNECTERROR] = false;
								txtWarn.setText(getError());
								return;
							}
							if (rs == 1) {
								txtEmailSignUp
										.setBackgroundResource(R.color.pink);
								mErrorList[EMAILEXISTED] = false;
								txtWarn.setText(getError());
								return;
							} else {
								mErrorList[EMAILCONNECTERROR] = true;
								mErrorList[EMAILEXISTED] = true;
								mErrorList[EMAILINVALID] = true;
								txtEmailSignUp
										.setBackgroundResource(R.color.light_green);
								txtWarn.setText(getError());
							}
						};
					}.execute();
				} else {
					txtEmailSignUp.setBackgroundResource(R.color.pink);
					mErrorList[EMAILINVALID] = false;
				}
				txtWarn.setText(getError());
				break;
			case R.id.login_txtPasswordSignup:
				String password = txtPassSignUp.getText().toString();
				if (txtPassSignUp.getText().length() == 0) {
					txtPassSignUp.setBackgroundResource(R.color.white);
				} else if (Utilities.checkValPass(password)) {
					txtPassSignUp.setBackgroundResource(R.color.light_green);
					mErrorList[PASSINVALID] = true;
				} else {
					txtPassSignUp.setBackgroundResource(R.color.pink);
					mErrorList[PASSINVALID] = false;
				}
				txtWarn.setText(getError());
				break;
			
			}
			
		}

	}

}
